package com.eco.fanliapp.controller.app;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eco.fanliapp.common.base.BaseController;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.DateUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2019-09-09
 */
@RestController
@RequestMapping("/app/syTimePeriod")
public class SyTimePeriodController extends BaseController {

    @Autowired
    private ISyTimePeriodService iSyTimePeriodService;
    @Autowired
    private ITaoBaoService iTaoBaoService;
    @Autowired
    private ISyTimePeriodGoodsService iSyTimePeriodGoodsService;
    @Autowired
    private ISyModuleService iSyModuleService;
    @Autowired
    private RedisTemplateService redisTemplateService;

    @GetMapping(value = "homePageList")
    public ServerResponse homePageList(@RequestParam(defaultValue = "0") Integer pageNum, @RequestParam(defaultValue = "3") Integer pageSize) {


//        return ServerResponse.createBySuccessCodeMessage(201, "没有更多商品");
        AppUser appUser = getAppUser();
        JSONObject jsonObject = new JSONObject();
        SyModule syModule = iSyModuleService.getById(7);//
        if (!syModule.getEnable()) return ServerResponse.createBySuccessCodeMessage(201, "查询为空");
        List<SyTimePeriod> syTimePeriodList = iSyTimePeriodService.syTimePeriodList(pageNum, pageSize, new Date().getHours() - 1, 0);
        if (syTimePeriodList.size() < 3) {
            syTimePeriodList = iSyTimePeriodService.syTimePeriodList(pageNum, pageSize, new Date().getHours() - 1, 1);
            Collections.reverse(syTimePeriodList);
        }
        jsonObject.put("syTimePeriodList", syTimePeriodList);
        long sysTime = System.currentTimeMillis();
        long countDown = sysTime;
        String s = DateUtils.date2Str(new Date(), DateUtils.DATE_FORMAT_YYYYMMDD);
        Long userId = null;
        if (appUser != null) {
            userId = appUser.getUserId();
        }
        for (SyTimePeriod syTimePeriod : syTimePeriodList) {
            List<SyTimePeriodGoods> syTimePeriodGoodsList = syTimePeriod.getSyTimePeriodGoodsList();

            syTimePeriodGoodsList = iTaoBaoService.calculatedGoodsCommission(userId, syTimePeriodGoodsList);
            syTimePeriod.setSyTimePeriodGoodsList(syTimePeriodGoodsList);
//            jsonObject.put("syTimePeriodList",syTimePeriodGoodsList);
        }
        for (SyTimePeriod syTimePeriod : syTimePeriodList) {
            String startTimeStr = s + " " + syTimePeriod.getPeriodTime() + ":00";
            long startTime = DateUtils.datestr2Date(startTimeStr, DateUtils.DATE_FORMAT_YYYYMMDDHHMMSS).getTime();
            if (startTime > sysTime) {
                countDown = startTime - sysTime;
                break;
            }
        }
        jsonObject.put("countDown", countDown);
        return ServerResponse.createBySuccess("查询成功", jsonObject);
    }

    @GetMapping(value = "list")
    public ServerResponse list(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "20") Integer pageSize) {
//        return ServerResponse.createBySuccessCodeMessage(201, "没有更多商品");
        String key = "app_index_syTimePeriod_list";
        IPage iPage = null;
        if (redisTemplateService.hasKey(key)) {
            iPage = redisTemplateService.get(key, IPage.class);
        } else {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("enable", 1);
            queryWrapper.eq("deleted", 0);
            Page<SyTimePeriod> page = new Page<>(pageNum, pageSize);
            iPage = iSyTimePeriodService.page(page, queryWrapper);
            redisTemplateService.set(key, iPage, 60 * 60 * 24);
        }
        List<SyTimePeriod> syTimePeriodList = iPage.getRecords();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("iPage", iPage);
        int hours = new Date().getHours();
        for (SyTimePeriod syTimePeriod : syTimePeriodList) {
            String periodTime = syTimePeriod.getPeriodTime();
            String[] split = periodTime.split(":");
            Integer integer = Integer.valueOf(split[0]);
            if (hours > integer) {
                syTimePeriod.setStatus(1);//已开抢
            }
            if (hours == integer || hours == integer + 1) {
                syTimePeriod.setStatus(2);//抢购中
            }
        }
        return ServerResponse.createBySuccess("查询成功", iPage);
    }

    /**
     * 刷新限时秒杀商品详情接口
     *
     * @param itemId
     * @return
     */
    @GetMapping("/refresh/details")
    public ServerResponse timePeriodRefreshDetails(Long itemId) {
        AppUser user = getAppUser();
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(301, "Token不正确");
        }
        return iSyTimePeriodService.timePeriodRefreshDetails(itemId, user.getUserId());
    }
}
